'use strict';
const WebSocket = require('ws'), https = require('https'), http = require('http'), fs = require('fs');
let sPort = 9099, mconfig = "loginM", ishttp = false;
if (process.argv[2]) sPort = process.argv[2];
if (process.argv[3]) mconfig = process.argv[3];
if (process.argv[4]) ishttp = process.argv[4];

global.LOG = require("./module/wloger").init(mconfig);
/** 用户缓存字典 */
global.USERMAP = {};

process.on('uncaughtException', function(err) {
    LOG.error('uncaughtException: ', err.stack);
});

let server = null;
if(ishttp){
    server = new http.createServer();
    //console.log("http");
}else{
    server = new https.createServer({
        cert: fs.readFileSync('STAR.banttt.com.crt'),
        key: fs.readFileSync('STAR.banttt.com.key')
    });
}

const wss = new WebSocket.Server({server}, ()=>{
    LOG.error("server run ok", sPort);
});

server.listen(sPort, ()=>{
    LOG.error("httpserver run ok", sPort);
});
 
wss.on('connection', function (ws, req) {
    ws.on('message', function(m){
        try{
            LOG.info('R', ws.U && ws.U.uid || 0, m);
            let jm = JSON.parse(m);
            let mc = require("./config/" + mconfig);
            if(jm[0] in mc){
                if(!ws.U && jm[0] > 0){
                    ws.send("[0,101,1]");
                    return;
                }
                let mod = require(mc[jm[0]]);
                mod.run(jm, ws, req);
            }else{
                LOG.error("msg not find", m);
            }
        }catch(e){
            LOG.error("json error", e, m, e.stack);
            //ws.close();
        }
    });
    ws.on("error", function(e){
        LOG.error(e);
        LOG.error("error", ws.U && ws.U.uid || 0);
        ws.close();
    });
    ws.on("close", function(){
        LOG.error("close", ws.U && ws.U.uid || 0);
        let mc = require("./config/" + mconfig);
        let mod = require(mc["99"]);
        mod.run(null, ws);
    })
});

//开启http接受后台通知
let httpc = require("./httpc");

//游戏退出时
process.on('exit', (code) => {
    LOG.error("exit", code);
    for(let u in USERMAP){
        USERMAP[u].close();
    }
    let gm = require("./mod/game");
    gm.exit();
});

//------------------------------------------------------------------------------------------------------------
//命令行处理
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.on('line', (chunk)=>{
    if (chunk !== null) {
        var da = chunk.toString('utf8', 0, chunk.length - 2).split(' ');
        if (da[0] == 'reload') {
            //如\login\ext.js
            if (require.cache[__dirname + da[1]]) {
                var md = require(__dirname + da[1]);
                if (md.destroy) {
                    md.destroy();
                }
                delete require.cache[__dirname + da[1]];
                console.log(da[1] + ' cache is delete');
                require(__dirname + da[1]);
            } else {
                console.log(da[1] + ' not cache');
            }
        } else if(da[0] == 'eval'){
            da = da.slice(1);
            eval(da.join(" "));
        }
    }
});

